package com.taxshare.purchaser.util;

import cn.hutool.core.date.DateUtil;
import com.taxshare.purchaser.entity.InvoiceCollectionEntity;
import com.taxshare.purchaser.entity.InvoiceDetailEntity;
import com.taxshare.tools.util.AreaCodeUtil;
import com.taxshare.tools.util.BeanSelfUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @Author: Liujt
 * 绘制虚拟票面信息
 */
@Slf4j
@Service
@SuppressWarnings("all")
public final class GraphicsInvoiceUtil {

    private static String typeface = "哥特字体";

    private GraphicsInvoiceUtil() {

    }

    /**
     * 通用发票
     *
     * @param vo
     * @param list
     * @param templateUrl
     * @return
     * @throws IOException
     */
    public static BufferedImage graphicsGenerationForInvoiceImage(InvoiceCollectionEntity vo, List<InvoiceDetailEntity> list, URL templateUrl) throws IOException {
        log.info("templateUrl:" + templateUrl);
        BufferedImage image = javax.imageio.ImageIO.read(templateUrl);
        Graphics graphics = image.getGraphics();
        //发票代码（134,50）
        graphics.setColor(new Color(181, 176, 166));
        graphics.setFont(new Font(typeface, Font.PLAIN, 24));
        graphics.drawString(Optional.ofNullable(vo.getInvoiceCode()).orElse(""), 134, 50);

        //校验码（134,50）
        graphics.setColor(new Color(118, 137, 170));
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(Optional.ofNullable(vo.getCheckCode()).orElse(""), 134, 85);

        //抬头（330,66）
        graphics.setColor(new Color(167, 116, 90));
        graphics.setFont(new Font(typeface, Font.BOLD, 16));
        String area2 = "";

        Map mapArea = AreaCodeUtil.recoginizeArea(vo.getInvoiceCode());
        String area = mapArea.get("fpssqymc") == null ? "" : mapArea.get("fpssqymc").toString();
        area2 = mapArea.get("fpssqymc2") == null ? "" : mapArea.get("fpssqymc2").toString();
        switch (vo.getInvoiceType()) {
            case "01":
                graphics.drawString(area + "增值税专用发票", 370, 43);
                break;
            default:
                graphics.drawString(area + "增值税普通发票", 370, 43);
                break;
        }


        //印章中心（390,66）
        graphics.setColor(Color.RED);
        graphics.setFont(new Font(typeface, Font.PLAIN, 14));
        graphics.drawString(area2, 410, 66);

        //发票号码（612,50）
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 24));
        graphics.drawString(Optional.ofNullable(vo.getInvoiceNo()).orElse(""), 610, 50);

        //小字体的发票代码
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(Optional.ofNullable(vo.getInvoiceCode()).orElse(""), 736, 50);

        //小字体的发票号码
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 18));
        graphics.drawString(Optional.ofNullable(vo.getInvoiceNo()).orElse(""), 736, 70);

        //开票日期（660，90）
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        if (!StringUtils.isEmpty(vo.getInvoiceDate())) {
            graphics.drawString(getFormatPaperDrewDateStr(vo.getInvoiceDate()), 680, 86);
        }
        //购方名称(164,123)
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(Optional.ofNullable(vo.getPurchaserName()).orElse(""), 168, 119);

        //购方税号(164,144)
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(Optional.ofNullable(vo.getPurchaserTaxNo()).orElse(""), 168, 138);

        //地址、电话(164,162)GFDZDH
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        String GFDZDH = Optional.ofNullable(vo.getPurchaserAddrPhone()).orElse("");
        if (GFDZDH.length() > 35) {graphics.setFont(new Font(typeface, Font.PLAIN, 10));}
        graphics.drawString(GFDZDH, 168, 157);

        //开户行及账号(164,186)GFYHZH
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        String GFYHZH = StringTools.stripToEmpty(vo.getPurchaserBrank());
        if (GFYHZH.length() > 35) {graphics.setFont(new Font(typeface, Font.PLAIN, 10));}
        graphics.drawString(GFYHZH, 168, 177);

        //判断有没有密文和密文长度：MWQ
        if (StringUtils.isNotBlank(vo.getCipherText())) {
            int invpwds = pwdlength(vo.getCipherText());
            graphics.setColor(Color.blue);
            graphics.setFont(new Font(typeface, Font.PLAIN, 12));
            graphics.drawString(vo.getCipherText().substring(0, invpwds), 520, 119);

            graphics.setColor(Color.blue);
            graphics.setFont(new Font(typeface, Font.PLAIN, 12));
            graphics.drawString(vo.getCipherText().substring(invpwds, 2 * invpwds), 520, 138);

            graphics.setColor(Color.blue);
            graphics.setFont(new Font(typeface, Font.PLAIN, 12));
            graphics.drawString(vo.getCipherText().substring(2 * invpwds, 3 * invpwds), 520, 157);

            graphics.setColor(Color.blue);
            graphics.setFont(new Font(typeface, Font.PLAIN, 12));
            graphics.drawString(vo.getCipherText().substring(3 * invpwds, 4 * invpwds), 520, 177);
        }
        details(list, graphics);

        //未税金额合计538,347
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString("￥ " + vo.getAmountWithOutTax() == null ? "" : vo.getAmountWithOutTax(), 590, 347);

        //税额
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString("￥ " + vo.getTaxAmount() == null ? "" : vo.getTaxAmount(), 735, 347);

        //价税合计（大写）
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getAmountWithTax() == null ? "" : BeanSelfUtils.change(Double.valueOf(vo.getAmountWithTax())), 280, 370);
        //价税合计小写
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getAmountWithTax() == null ? "" : vo.getAmountWithTax(), 690, 370);

        //销方名称(164,123)
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(Optional.ofNullable(vo.getSellerName()).orElse(""), 168, 395);

        //销方税号(164,144)
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(Optional.ofNullable(vo.getSellerTaxNo()).orElse(""), 168, 412);

        //销地址、电话(164,162)
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        String XFDZDH = Optional.ofNullable(vo.getSellerAddrPhone()).orElse("");
        if (XFDZDH.length() > 35) {graphics.setFont(new Font(typeface, Font.PLAIN, 10));}
        graphics.drawString(XFDZDH, 168, 429);

        //销开户行及账号(164,186)
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        String XFYHZH = Optional.ofNullable(vo.getSellerBrank()).orElse("");
        if (XFYHZH.length() > 35) {graphics.setFont(new Font(typeface, Font.PLAIN, 10));}
        graphics.drawString(XFYHZH, 168, 446);

        //备注invcomment
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(Optional.ofNullable(vo.getRemark()).orElse(""), 510, 405);

        //收款人
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(Optional.ofNullable(vo.getCashier()).orElse(""), 130, 470);

        //复核
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getReviewer() == null ? "" : vo.getReviewer(), 330, 470);

        //开票人
        graphics.setColor(Color.blue);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getDrawer() == null ? "" : vo.getDrawer(), 505, 470);

        return image;
    }

    private static String getFormatPaperDrewDateStr(String paperDrewDateStr) {
        String formatStr = null;
        try {
            Date date = DateUtil.parse(paperDrewDateStr);
            formatStr = DateUtil.format(date, "yyyy年MM月dd日");
        } catch (Exception e) {
            return "";
        }
        return formatStr;
    }

    private static void details(List<InvoiceDetailEntity> list, Graphics graphics) {
        //明细（）

        if (list.size() <= 8) {
            for (int i = 0; i < list.size(); i++) {
                InvoiceDetailEntity invoiceItem = list.get(i);
                //货物或应税劳务、服务名称
                graphics.setColor(Color.blue);
                graphics.setFont(new Font(typeface, Font.PLAIN, 11));
                String spmc = invoiceItem.getGoodsName();
                String spjc = "";
                if (!"".equals(spjc)) {spmc = "*" + spjc + "*" + spmc;}

                if (spmc.length() > 16) {spmc = spmc.substring(0, 14) + "...";}
                graphics.drawString(spmc, 73, 215 + 16 * i);

                //规格型号
                graphics.setColor(Color.blue);
                graphics.setFont(new Font(typeface, Font.PLAIN, 10));
                String ggxh = StringTools.stripToEmpty(invoiceItem.getModel());
                if (ggxh.length() > 8) {ggxh = ggxh.substring(0, 7) + "...";}
                graphics.drawString(ggxh, 235, 215 + 16 * i);

                //单位
                graphics.setColor(Color.blue);
                graphics.setFont(new Font(typeface, Font.PLAIN, 12));
                graphics.drawString(invoiceItem.getUnit(), 320, 215 + 16 * i);

                //数量
                graphics.setColor(Color.blue);
                graphics.setFont(new Font(typeface, Font.PLAIN, 12));
                graphics.drawString(null == invoiceItem.getGoodsNumber() ? "" : invoiceItem.getGoodsNumber() + "", 370, 215 + 16 * i);

                //单价
                graphics.setColor(Color.blue);
                graphics.setFont(new Font(typeface, Font.PLAIN, 12));
                graphics.drawString(null == invoiceItem.getUnitPriceOutTax() ? "" : invoiceItem.getUnitPriceOutTax() + "", 480, 215 + 16 * i);

                //金额
                graphics.setColor(Color.blue);
                graphics.setFont(new Font(typeface, Font.PLAIN, 12));
                graphics.drawString(null == invoiceItem.getAmountWithOutTax() ? "" : invoiceItem.getAmountWithOutTax() + "", 590, 215 + 16 * i);

                //税率
                graphics.setColor(Color.blue);
                graphics.setFont(new Font(typeface, Font.PLAIN, 12));
                String slv = "";
                String taxRate = invoiceItem.getTaxRate();

                if (taxRate.contains("\\.")) {
                    graphics.drawString(taxRate.split("\\.")[1] + "%", 697, 215 + 16 * i);
                    slv = taxRate.split("\\.")[1];
                }

                if (slv.equals("")) {graphics.drawString(taxRate + "%", 697, 215 + 16 * i);}

                //税额
                graphics.setColor(Color.blue);
                graphics.setFont(new Font(typeface, Font.PLAIN, 12));
                graphics.drawString(invoiceItem.getTaxAmount() + "", 735, 215 + 16 * i);

            }
        } else {
            //货物或应税劳务、服务名称
            graphics.setColor(Color.blue);
            graphics.setFont(new Font(typeface, Font.PLAIN, 12));
            graphics.drawString("(详见货物清单)", 83, 215);
        }
    }


    /**
     * 卷式发票
     *
     * @param vo
     * @param list
     * @param templateUrl
     * @return
     */
    public static BufferedImage graphicsForVolumeInvoiceImage(InvoiceCollectionEntity vo, List<InvoiceDetailEntity> list, URL templateUrl) throws IOException {
        BufferedImage image = javax.imageio.ImageIO.read(templateUrl);
        Graphics graphics = image.getGraphics();
        Color color = new Color(100, 100, 100);
        //发票代码（134,50）
        graphics.setColor(color);
        graphics.setFont(new Font(typeface, Font.PLAIN, 20));
        graphics.drawString(vo.getInvoiceCode(), 90, 140);

        //发票号码（612,50）
        graphics.setColor(color);
        graphics.setFont(new Font(typeface, Font.PLAIN, 20));
        graphics.drawString(Optional.ofNullable(vo.getInvoiceNo()).orElse(""), 90, 162);

        //机器编号
        graphics.setColor(color);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getMachineCode(), 245, 185);

        //销方名称
        graphics.setColor(color);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getSellerName(), 98, 208);

        //销方税号
        graphics.setColor(color);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getSellerTaxNo(), 110, 245);

        //开票日期
        graphics.setColor(color);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        if (!StringUtils.isEmpty(vo.getInvoiceDate())) {
            graphics.drawString(vo.getInvoiceDate().substring(0, 4) + "年"
                    + vo.getInvoiceDate().substring(4, 6) + "月" + vo.getInvoiceDate().substring(6, 8) + "日", 80, 264);
        }
        //购方名称
        graphics.setColor(color);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getPurchaserName(), 95, 284);

        //销方税号
        graphics.setColor(color);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getPurchaserTaxNo(), 110, 320);
        volumeDetails(list, graphics, color);

        //价税合计小写
        graphics.setColor(color);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getAmountWithTax() == null ? "" : vo.getAmountWithTax(), 115, 562);

        //价税合计（大写）
        graphics.setColor(color);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getAmountWithTax() == null ? "" : BeanSelfUtils.change(Double.valueOf(vo.getAmountWithTax())), 116, 585);

        //校验码
        graphics.setColor(color);
        graphics.setFont(new Font(typeface, Font.PLAIN, 12));
        graphics.drawString(vo.getCheckCode() == null ? "" : vo.getCheckCode(), 68, 608);

        return image;
    }

    private static void volumeDetails(List<InvoiceDetailEntity> list, Graphics graphics, Color color) {
        //明细（）
        if (list.size() > 8) {
            //货物或应税劳务、服务名称
            graphics.setColor(color);
            graphics.setFont(new Font(typeface, Font.PLAIN, 12));
            graphics.drawString("(详见货物清单)", 83, 215);
        } else {
            for (int i = 0; i < list.size(); i++) {
            InvoiceDetailEntity invoiceItem = list.get(i);
            //货物或应税劳务、服务名称
            graphics.setColor(color);
            graphics.setFont(new Font(typeface, Font.PLAIN, 11));
            String spmc = invoiceItem.getGoodsName();
            String spjc = "";
            if (!"".equals(spjc)) {spmc = "*" + spjc + "*" + spmc;}

            if (spmc.length() > 16) {spmc = spmc.substring(0, 14) + "...";}
            graphics.drawString(spmc, 25, 360 + 16 * i);

            //单价
            graphics.setColor(color);
            graphics.setFont(new Font(typeface, Font.PLAIN, 12));
            graphics.drawString(null == invoiceItem.getUnitPrice() ? "" : invoiceItem.getUnitPrice() + "", 125, 360 + 16 * i);

            //数量
            graphics.setColor(color);
            graphics.setFont(new Font(typeface, Font.PLAIN, 12));
            graphics.drawString(null == invoiceItem.getGoodsNumber() ? "" : invoiceItem.getUnitPrice() + "", 190, 360 + 16 * i);

            //金额
            graphics.setColor(color);
            graphics.setFont(new Font(typeface, Font.PLAIN, 12));
            graphics.drawString(invoiceItem.getAmountWithTax() + "", 283, 360 + 16 * i);
        }
      }
    }


    public static int pwdlength(String invpwd) {
        int pwd4L = invpwd.length();
        int pwdL = pwd4L / 4;
        return pwdL;
    }

}
 
  